﻿using System;
using System.Globalization;
using System.Net.Http;
using Microsoft.Owin;
using Microsoft.Owin.Logging;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.DataHandler;
using Microsoft.Owin.Security.DataProtection;
using Microsoft.Owin.Security.Infrastructure;
using Owin;
using Sharp.Platform.Owin.OAuth.Baidu.Provider;

namespace Sharp.Platform.Owin.OAuth.Baidu
{
    public class AuthenticationMiddleware : AuthenticationMiddleware<BaiduAuthenticationOptions>
    {
        private readonly HttpClient _httpClient;
        private readonly ILogger _logger;

        public AuthenticationMiddleware(OwinMiddleware next, IAppBuilder app,
            BaiduAuthenticationOptions options)
            : base(next, options)
        {
            if (string.IsNullOrWhiteSpace(Options.ApiKey))
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
                    "The '{0}' option must be provided.", nameof(Options.ApiKey)));
            if (string.IsNullOrWhiteSpace(Options.SecretKey))
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
                    "The '{0}' option must be provided.", nameof(Options.SecretKey)));

            _logger = app.CreateLogger<AuthenticationMiddleware>();

            if (Options.Provider == null)
                Options.Provider = new BaiduAuthenticationProvider();

            if (Options.StateDataFormat == null)
            {
                var dataProtector = app.CreateDataProtector(
                    typeof (AuthenticationMiddleware).FullName,
                    Options.AuthenticationType, "v1");
                Options.StateDataFormat = new PropertiesDataFormat(dataProtector);
            }

            if (string.IsNullOrEmpty(Options.SignInAsAuthenticationType))
                Options.SignInAsAuthenticationType = app.GetDefaultSignInAsAuthenticationType();

            _httpClient = new HttpClient(ResolveHttpMessageHandler(Options))
            {
                Timeout = Options.BackchannelTimeout,
                MaxResponseContentBufferSize = 1024*1024*10
            };
        }

        protected override AuthenticationHandler<BaiduAuthenticationOptions> CreateHandler()
        {
            return new AuthenticationHandler(_httpClient, _logger);
        }

        private static HttpMessageHandler ResolveHttpMessageHandler(BaiduAuthenticationOptions options)
        {
            var handler = options.BackchannelHttpHandler ?? new WebRequestHandler();

            // If they provided a validator, apply it or fail.
            if (options.BackchannelCertificateValidator == null) return handler;
            // Set the cert validate callback
            var webRequestHandler = handler as WebRequestHandler;
            if (webRequestHandler == null)
            {
                throw new InvalidOperationException("An ICertificateValidator cannot be specified at the same time as an HttpMessageHandler unless it is a WebRequestHandler.");
            }
            webRequestHandler.ServerCertificateValidationCallback = options.BackchannelCertificateValidator.Validate;

            return handler;
        }
    }
}